import React, { createContext, useContext, useState, ReactNode } from 'react';

export interface DownloadItem {
  id: string;
  title: string;
  size: number;
  progress: number;
  status: 'downloading' | 'paused' | 'completed' | 'error';
  speed: number;
  timeRemaining: number;
  error?: string;
}

interface DownloadContextType {
  downloads: DownloadItem[];
  pauseDownload: (id: string) => void;
  resumeDownload: (id: string) => void;
  removeDownload: (id: string) => void;
  addDownload: (download: Omit<DownloadItem, 'id'>) => void;
}

const DownloadContext = createContext<DownloadContextType | null>(null);

export const useDownload = () => {
  const context = useContext(DownloadContext);
  if (!context) {
    throw new Error('useDownload must be used within a DownloadProvider');
  }
  return context;
};

interface DownloadProviderProps {
  children: ReactNode;
}

export const DownloadProvider: React.FC<DownloadProviderProps> = ({ children }) => {
  const [downloads, setDownloads] = useState<DownloadItem[]>([{
    id: '1',
    title: '泰勒·斯威夫特2024巡回演唱会.mp4',
    size: 2147483648, // 2GB
    progress: 45,
    status: 'downloading',
    speed: 1048576, // 1MB/s
    timeRemaining: 1200 // 20分钟
  }, {
    id: '2',
    title: 'Photoshop 2024完整教程.zip',
    size: 4294967296, // 4GB
    progress: 100,
    status: 'completed',
    speed: 0,
    timeRemaining: 0
  }, {
    id: '3',
    title: '星际穿越4K蓝光版.mkv',
    size: 8589934592, // 8GB
    progress: 60,
    status: 'paused',
    speed: 0,
    timeRemaining: 3600 // 1小时
  }, {
    id: '4',
    title: '周一促销资源包.rar',
    size: 1073741824, // 1GB
    progress: 30,
    status: 'error',
    speed: 0,
    timeRemaining: 0,
    error: '网络连接中断'
  }]);

  const pauseDownload = (id: string) => {
    setDownloads(prevDownloads =>
      prevDownloads.map(download =>
        download.id === id
          ? { ...download, status: 'paused' as const, speed: 0 }
          : download
      )
    );
  };

  const resumeDownload = (id: string) => {
    setDownloads(prevDownloads =>
      prevDownloads.map(download =>
        download.id === id
          ? { ...download, status: 'downloading' as const }
          : download
      )
    );
  };

  const removeDownload = (id: string) => {
    setDownloads(prevDownloads =>
      prevDownloads.filter(download => download.id !== id)
    );
  };

  const addDownload = (download: Omit<DownloadItem, 'id'>) => {
    const newDownload: DownloadItem = {
      ...download,
      id: Math.random().toString(36).substr(2, 9),
    };
    setDownloads(prevDownloads => [...prevDownloads, newDownload]);
  };

  return (
    <DownloadContext.Provider
      value={{
        downloads,
        pauseDownload,
        resumeDownload,
        removeDownload,
        addDownload,
      }}
    >
      {children}
    </DownloadContext.Provider>
  );
};